import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MyThreadPool {
    //阻塞队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(50);
    //定义最大线程数
    private int maxPoolSize = 10;
    //使用顺序表来记录个数
    List list = new ArrayList();
    //创建若干线程,个数为传入的核心线程数
    public MyThreadPool(int corePoolSize,int maxPoolSize) {
        for (int i = 0; i < corePoolSize; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true){
                            Runnable runnable = queue.take();
                            runnable.run();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
            list.add(t);
        }
    }
    void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
        //超过阈值并且线程数量没有超过最大线程数
        if(queue.size() >= 500 && list.size() < maxPoolSize) {
            //创建新的线程
            Thread t = new Thread(()->{
                while (true) {
                    try {
                        Runnable task  = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }
}
